<script lang="ts">
export default {
  name: 'dept'
};
</script>

<script setup lang="ts">
import Edit from './components/edit.vue';
import {
  deleteListDept,
  deleteDept,
  updateDept,
  addDept,
  listDeptOptions,
  listDepts
} from '@/api/dept';

import { DeptVO, DeptForm, DeptQuery } from '@/api/dept/types';
import { statusOptionList } from '@/option'
import { tree } from '@/utils/utils'

const queryFormRef = ref(ElForm);
const deptFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);

const queryParams: any = reactive({
  current: 1,
  pageSize: 9999,
});

const formData = reactive({
  status: 1,
  parentId: 0,
  orderNum: 1
});

const dialog = reactive({
  visible: false,
});

const deptList = ref<any>([]);

const deptOptions = ref<any>();

const stgStr = ref('edit')

const rules = reactive({
  // parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }]
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  let a: any = {
    "pageSize": 9999,
    "current": 1
  }
  let b: any = { ...queryParams, ...a }
  //TODO 解决后端由树结构变为分页结构，把所有数据查出来前端自己处理先
  listDepts(a).then((res) => {
    deptList.value = tree(res.data.data, 0, 'parentId')
    loading.value = false;
  });
}

/**
 * 重置查询
 */
function resetQuery() {
  // queryFormRef.value.resetFields();
  handleQuery();
}

/**
 * 行复选框选中记录选中ID集合
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param row 行数据
 * @param stg 字符串
 */
async function openDialog(row?: any, stg: string = 'edit') {
  dialog.visible = true;
  stgStr.value = stg

  if (stg === 'edit') {
    row && Object.assign(formData, row)
    dialog.title = '修改商品分类';
  } else {
    row && Object.assign(formData, { parentId: row.id })
    dialog.title = '新增商品分类';
  }
}

/**
 * 表单提交
 */
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (stgStr.value === 'edit') {
        updateDept(formData)
          .then(() => {
            ElMessage.success('修改成功');
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addDept(formData)
          .then(() => {
            ElMessage.success('新增成功');
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/**
 * 删除部门
 */
function handleDelete(id?: number) {
  let idList = ids.value
  id ? idList = [...ids.value, id] : null
  if (idList.length === 0) {
    ElMessage.warning('请勾选删除项');
    return;
  }
  ElMessageBox.confirm(`确认删除已选中的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteListDept(idList).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  formData.id = undefined;
  formData.parentId = 0;
  formData.status = 1;
  formData.orderNum = 1;
  if (deptFormRef.value && deptFormRef.value.resetFields) {
    deptFormRef.value.resetFields();
    deptFormRef.value.clearValidate();
  }
}

onMounted(() => {
  handleQuery();
});
</script>
<template>
  <div class="app-container">

    <el-card>
      <template #header>
        <el-button type="success" @click="openDialog(undefined, 'add')">
          <i-ep-plus />新增
        </el-button>
        <el-button type="danger" @click="handleDelete()" :disabled="ids.length === 0">
          <i-ep-delete />删除
        </el-button>
      </template>

      <el-table v-loading="loading" :data="deptList" row-key="id" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column label="图标" align="center" prop="status" width="120">
          <template #default="scope">
            <img class="icon-img" :src="scope.row.icon" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="name" label="分类级别" />
        <el-table-column prop="name" label="产品数量" />
        <el-table-column prop="name" label="是否显示在导航栏" />
        <el-table-column prop="name" label="显示状态" />
        <el-table-column prop="orderNum" label="排序" width="100" />
        <el-table-column prop="name" label="关键字" />
        <el-table-column prop="name" label="描述" />

        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button type="primary" link size="small" @click.stop="openDialog(scope.row, 'edit')">
              <i-ep-edit />编辑
            </el-button>
            <el-button type="primary" link size="small" @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <Edit :dialog="dialog" :formData="formData" @resetQuery="resetQuery"></Edit>
  </div>
</template>

<style lang="scss" scoped>
.icon-img {
  width: 100px;
}
</style>